<template>
  <el-card body-style="min-height: 86vh">
    <!-- 搜索 -->
    <el-form :model="searchForm" label-width="100px">
      <el-row :gutter="10">
        <el-col :span="6">
          <el-form-item label="车牌号">
            <el-input v-model="searchForm.licensePlate" placeholder="请输入车牌号"></el-input>
          </el-form-item>
        </el-col>
        <!-- <el-col :span="6">
          <el-form-item label="汽修站">
            <el-select
              v-model="searchForm.inspectionId"
              placeholder="请选择汽修站"
              filterable
            ></el-select>
          </el-form-item>
        </el-col> -->
        <el-col :span="6">
          <el-form-item>
            <el-button @click="handleRestSearch()">重置</el-button>
            <el-button type="primary" @click="handleGetTableList()">搜索</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-divider />
    <!-- 新增、筛选按钮 -->
    <div class="flex justify-between">
      <div>
        <el-button v-permission="['second:record:add']" type="primary" @click="handleAddRecord">新增维修档案</el-button>
      </div>
      <div>
        <el-button circle @click="handleGetTableList()">
          <template #icon><el-icon>
              <Refresh />
            </el-icon></template>
        </el-button>
      </div>
    </div>
    <el-table :data="tableData">
      <el-table-column label="报告单" width="100" align="center">
        <template #default="{ row }">
          <el-image preview-teleported :src="row.report" :z-index="100" style="width: 100px; height: 100px"
            :preview-src-list="[row.report]">
          </el-image>
        </template>
      </el-table-column>
      <el-table-column prop="licensePlate" label="车牌号" width="120" align="center" />
      <el-table-column prop="repairName" label="承修单位" width="220" align="center" />
      <el-table-column prop="qualityInspector" label="质量检验员" width="120" align="center" />
      <el-table-column prop="companyName" label="托修方" width="220" align="center" />
      <el-table-column prop="inspectionName" label="检测站" width="220" align="center" />
      <el-table-column prop="repairDate" label="进厂日期" width="120" align="center">
        <template #default="{ row }">
          {{ dayjs(row.repairDate).format("YYYY-MM-DD") }}
        </template>
      </el-table-column>
      <el-table-column prop="leaveDate" label="出厂日期" width="120" align="center">
        <template #default="{ row }">
          {{ row.leaveDate && dayjs(row.leaveDate).format("YYYY-MM-DD") }}
        </template>
      </el-table-column>
      <el-table-column prop="acceptDate" label="接车日期" width="120" align="center">
        <template #default="{ row }">
          {{ dayjs(row.acceptDate).format("YYYY-MM-DD") }}
        </template>
      </el-table-column>
      <el-table-column prop="report" label="上传状态" width="120" align="center" fixed="right">
        <template #default="{ row }">
          <el-button text :type="row.report ? 'success' : 'danger'">{{
            row.report ? "已上传" : "未上传"
          }}</el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" width="300" align="center">
        <template #default="{ row }">
          <el-button type="primary" class="mb-2" @click="handleViewRecord(row)">查看</el-button>
          <el-button v-permission="['second:record:edit']" v-if="!row.report" type="primary" class="mb-2"
            @click="handleEditRecord(row)">编辑</el-button>
          <el-button v-permission="['second:contract:down']" v-if="!row.report" type="primary" class="mb-2"
            @click="handleDownContract(row)">下载合同</el-button>
          <el-button v-permission="['second:contract:upload']" v-if="!row.report" type="primary" class="mb-2"
            @click="handleUploadContract(row)">上传合同</el-button>
          <el-button v-permission="['second:record:distribute']" v-if="!row.report" type="primary" class="mb-2"
            @click="handleCheckStation(row)">分配检测站</el-button>
          <el-button v-permission="['second:report:upload']" v-if="!row.report" type="primary" class="mb-2"
            @click="handleUploadReport(row)">上传报告单</el-button>
          <!-- <el-button type="primary" class="mb-2" @click="handleDelete(row)">高拍仪</el-button> -->
          <el-button v-permission="['second:report:print']" type="primary" class="mb-2"
            @click="handlePrint(row)">打印</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination class="flex justify-center mt-2" background layout="total,prev, pager, next"
      :current-page="currentPage" :page-size="limit" :total="total" @current-change="handleGetTableList" />
    <!-- 新增、编辑 -->
    <maintain-dialog ref="maintainRef" :isView="isView" :type="type" @success="handleGetTableList"></maintain-dialog>
    <!-- 下载合同 -->
    <down-contract ref="downContractRef"></down-contract>
    <!-- 上传合同 -->
    <upload-contract ref="uploadContractRef" :record="curRecord" @success="handleGetTableList"></upload-contract>
    <!-- 分配检测站 -->
    <distribute-station ref="distributeStationRef" :record="curRecord"
      @success="handleGetTableList"></distribute-station>
    <!-- 上传报告单 -->
    <upload-report ref="uploadReportRef" :recordId="curRecord.id" @success="handleGetTableList"></upload-report>
  </el-card>
</template>
<script setup lang="ts">
import dayjs from "dayjs";
import { ElMessage } from "element-plus";
import { defineAsyncComponent, ref } from "vue";
import { disAutoConnect, hiprint } from "vue-plugin-hiprint";
import { useInitTable } from "@/hooks/useCommon";
import mb from "./json/mb.json";
import { getSecondMaintainRecordListApi, getSecondMatainRecordDetailApi } from "@/api/second";

const MaintainDialog = defineAsyncComponent(() => import("./components/maintainDialog.vue"));
const DownContract = defineAsyncComponent(() => import("./components/downContract.vue"));
const UploadContract = defineAsyncComponent(() => import("./components/uploadContract.vue"));
const DistributeStation = defineAsyncComponent(() => import("./components/distributeStation.vue"));
const UploadReport = defineAsyncComponent(() => import("./components/uploadReport.vue"));

// 打印-取消自动连接
disAutoConnect();
// 表格
const { searchForm, tableData, currentPage, limit, total, handleRestSearch, handleGetTableList } =
  useInitTable({
    searchForm: {
      licensePlate: ""
    },
    getTableList: getSecondMaintainRecordListApi
  });
// 选择维修记录
const curRecord = ref<any>({});
// 新增维修档案
const maintainRef = ref(null);
// 配件是否是查看
const isView = ref(false);
// 标题
const type = ref(1);
const handleAddRecord = () => {
  // form.projectList && (form.projectList.length = 0);
  isView.value = false;
  type.value = 1;
  (maintainRef.value as any).form.projectList && ((maintainRef.value as any).form.projectList.length = 0);
  (maintainRef.value as any).handleCreate();
};
// 查看
const handleViewRecord = async (val: any) => {
  const res: any = await handelGetRecordDetail(val.id);

  new Array("carImgFront", "carImgBack", "carImgLeft", "carImgRight").forEach(async item => {
    const data = await fetch(res[item], {
      headers: { "Cache-Control": "no-cache" }
    })
    const blob = await data.blob()
    const baseUrl = URL.createObjectURL(blob)
    val[item] = baseUrl
    res[item] = baseUrl
  })

  isView.value = true;
  type.value = 3;
  (maintainRef.value as any).handleEdit({
    ...res,
    carImgFront1: [{ url: val.carImgFront }],
    carImgBack1: [{ url: val.carImgBack }],
    carImgLeft1: [{ url: val.carImgLeft }],
    carImgRight1: [{ url: val.carImgRight }]
  });
};

// 编辑
const handleEditRecord = async (val: any) => {
  const res: any = await handelGetRecordDetail(val.id);
  isView.value = false;
  type.value = 2;
  (maintainRef.value as any).handleEdit({
    ...res,
    carImgFront1: [{ url: val.carImgFront }],
    carImgBack1: [{ url: val.carImgBack }],
    carImgLeft1: [{ url: val.carImgLeft }],
    carImgRight1: [{ url: val.carImgRight }]
  });
};
// 获取详情
const handelGetRecordDetail = async (id: number) => {
  return new Promise((resolve) => {
    try {
      getSecondMatainRecordDetailApi({ id }).then((res) => {
        resolve(res);
      });
    } catch (error) {
      console.log(error);
    }
  });
};
// 下载合同
const downContractRef = ref(null);
const handleDownContract = (row: any) => {
  (downContractRef.value as any).handleOpen(row.id);
};

// 上传合同
const uploadContractRef = ref(null);
const handleUploadContract = (row: any) => {
  curRecord.value = {
    id: row.id,
    contract: row.contract
  };
  (uploadContractRef.value as any).handleCreate();
};

//分配检测站
const distributeStationRef = ref(null);
const handleCheckStation = (val: any) => {
  curRecord.value = {
    recordId: val.id,
    inspectionId: val.inspectionId
  };
  (distributeStationRef.value as any).handleCreate();
};

// 上传报告
const uploadReportRef = ref(null);
const handleUploadReport = (val: any) => {
  curRecord.value = val;
  (uploadReportRef.value as any).handleCreate();
};

// 打印
const handlePrint = (val: any) => {
  if (!val.report) {
    return ElMessage.error("请先上传报告");
  }
  let hiprintTemplate = new hiprint.PrintTemplate({ template: mb });
  hiprintTemplate.print({
    qrcode: `http://localhost:9527/#/QRCodePage/${val.id}`,
    No: val.orderNo,
    carnumber: val.licensePlate,
    entrust: val.companyName,
    cartype: val.carBrand,
    engineNo: val.engineNo,
    vin: val.bodyNo,
    type: "二级维护",
    contractNo: val.contractNo,
    mileage: val.mileageNum,
    inDate: dayjs(val.repairDate).format("YYYY-MM-DD"),
    outDate: dayjs(val.leaveDate).format("YYYY-MM-DD"),
    commitment: `该车按维修合同维修，经检验合格，准予出厂，承修方对维修竣工的车辆实行质量保证，质量保证期为车辆行驶${val.qualityAssuranceMileage} 公里或者 ${val.qualityAssuranceDays} 日。在托修单位严格执行走合期规定、合理使用、正常维护的情况下，出现的维修质量问题，凭此证由承修方负责保修，免返修工料费和工时费，在原维修类别期限内修竣交托修方。`,
    qualityInspection: val.qualityInspector,
    repair: val.repairName,
    pickDate: dayjs(val.acceptDate).format("YYYY-MM-DD")
  });
};
</script>
<style scoped lang="scss">
.dialog-body {
  height: calc(100vh - 180px);
  overflow-y: auto;
}

.dialog-project {
  height: calc(100vh - 480px);
  overflow-y: auto;
}
</style>
